package com.pan.download1;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 把内容谢入文件的类
 */
public class Write {

    private FileWriter fileWriter;

    private String path;

    private String bookName;

    /**
     * 这个数字是用来控制写入的章节进度的
     */
    private int ctrlNum = -1;

    private ReentrantLock lock = new ReentrantLock();

    /**
     * 构造函数主要干了的事情：
     * 1. 把FileWrite类创建起来
     * 2. 把要写入的书本txt文件创建出来
     * @param path
     * @param bookName
     */
    public Write(String path,String bookName){
        this.bookName = bookName;
        this.path = path;
        String bookPath = path+"\\stroy\\"+bookName+".txt";
        try {
            fileWriter = new FileWriter(bookPath,true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        File file = new File(bookPath);
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        else {
            throw new RuntimeException("该书名已经存在");
        }
    }

    /**
     * 这个是使用默认路径
     * @param bookName
     */
    public Write(String bookName) {
        this.bookName = bookName;
        path = System.getProperty("user.dir");
        String bookPath = path+"\\story\\"+bookName+".txt";
        try {
            fileWriter = new FileWriter(bookPath,true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        File file = new File(bookPath);
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        else {
//            throw new RuntimeException("该书名已经存在");
        }

    }

    /**
     * 将内容追加到文件里面
     * @param num 这是章节的序号
     * @param content 这是传入内容
     * @return
     */
    public boolean appendContent(int num,String content){
        for (int i = 0; i < 2; i++) {
            if (num == ctrlNum+1){
                lock.lock();
                ctrlNum = num;
                try {
                    fileWriter.write(content);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 用完后关闭
     */
    public void close(){
        try {
            fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
